using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Inventory 
{
    bool full = false;
    private Slot[] slots;
    public void StoreItem(int id,int number)
    {
        Slot slot;
        int max = GameFacade.Instance.inventoryManager.Getitem(id).Capacity;
        slot = FindSameSlot(id);
        while (slot!=null)
        {
            if(max>=number+slot.number)
            {
                
                slot.number += number;
                slot.transform.GetChild(0).GetComponent<ItemUI>().SetNumber(slot.number);
                number = 0;
                return;
            }
            else
            {
                number -= max - slot.number;
                slot.number = max;
                slot.transform.GetChild(0).GetComponent<ItemUI>().SetNumber(slot.number);
                if (number == 0)
                    return;
                slot = FindSameSlot(id);
            }
        }
        slot = FindEmptySlot();
        while (slot != null)
        {
            if(max >= number)
            {
                slot.StoreItem(GameFacade.Instance.inventoryManager.Getitem(id), number);
                number = 0;
                return;
            }
            else
            {
                slot.StoreItem(GameFacade.Instance.inventoryManager.Getitem(id), max);
                number -= max;
                slot = FindEmptySlot();
            }
        }
        full = true;
        Debug.Log(full);
    }
   
    private Slot FindEmptySlot()
    {
        foreach (Slot slot in slots)
        {
            if (slot.transform.childCount == 0)
            {
                return slot;
            }
        }
        return null;
    }
    private Slot FindSameSlot(int id)
    {
        foreach (Slot slot in slots)
        {
            if(slot.transform.childCount != 0 && id == slot.Item.Id && slot.number < slot.Item.Capacity)
            {
                return slot;
            }
        }
        return null;
    }
    public void Init(GameObject g)
    {
        slots = g.GetComponentsInChildren<Slot>();
        
    }
   
}
